import { userStorage } from './storage'
import config from '@/config'
import { userApi } from '@/api'

// 显示手机号授权弹框
const showPhoneAuthModal = () => {
    return new Promise((resolve, reject) => {
        // 通过全局事件来控制弹框显示
        uni.$emit('showPhoneAuth', {
            success: (phoneData) => {
                resolve(phoneData)
            },
            fail: () => {
                reject(new Error('用户取消授权'))
            }
        })
    })
}

// 自动登录
const autoLogin = () => {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: 'weixin',
            success: (loginRes) => {
                userApi.wxLogin({
                    code: loginRes.code
                }).then(res => {
                    // 保存登录信息，包括 needPhone
                    userStorage.setToken(res.data.token)
                    userStorage.setUserInfo(res.data.userInfo)
                    userStorage.setNeedPhone(res.data.needPhone)
                    resolve(res)
                }).catch(reject)
            },
            fail: reject
        })
    })
}

const request = (options = {}) => {
    return new Promise((resolve, reject) => {
        const token = userStorage.getToken()
        
        uni.request({
            url: config.baseUrl + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'content-type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : '',
                ...options.header
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    if (res.data.code === 200) {
                        resolve(res.data)
                    } else if (res.data.code === 401) {
                        // 认证失败，尝试自动登录
                        autoLogin().then(() => {
                            // 登录成功后重试当前请求
                            request(options).then(resolve).catch(reject)
                        }).catch(err => {
                            reject(err)
                        })
                    } else {
                        uni.showToast({
                            title: res.data.msg || '请求失败',
                            icon: 'none'
                        })
                        reject(res.data)
                    }
                } else {
                    uni.showToast({
                        title: '服务器异常',
                        icon: 'none'
                    })
                    reject(res.data)
                }
            },
            fail: (err) => {
                uni.showToast({
                    title: '网络异常',
                    icon: 'none'
                })
                reject(err)
            }
        })
    })
}

export default request 